package util

import (
	"context"
	"fmt"
	"github.com/bwmarrin/snowflake"
	"github.com/tencentyun/cos-go-sdk-v5"
	"github.com/tencentyun/cos-go-sdk-v5/debug"
	"mime/multipart"
	"net/http"
	"net/url"
	"os"
	"strconv"
	"strings"
)

// TODO 敏感信息
const (
	COS_BUCKET_NAME = "douyin"
	COS_APP_ID      = "1304079174"
	COS_REGION      = "ap-nanjing"
	COS_SECRET_ID   = "AKIDb9YnuvlTAh3FG7mGZhIk172mW7WkmaAV"
	COS_SECRET_KEY  = "7yZYKrEOK5bswmLhpmXEn8HDxV5SaT7W"
	COS_URL_FORMAT  = "http://%s-%s.cos.%s.myqcloud.com" // 此项固定
	BASE_URL        = "https://douyin-1304079174.cos.ap-nanjing.myqcloud.com/"
)

func UploadFile(file multipart.File, key string) string {
	//雪花算法 生成id
	node, err2 := snowflake.NewNode(1)
	if err2 != nil {
		fmt.Println(err2)
	}
	id := node.Generate()
	key = strconv.FormatInt(id.Int64(), 10) + "-" + key
	c := getClient()
	_, err := c.Object.Put(context.Background(), key, file, nil)
	if log_status(err) {
		//getSnapshot(key)
		//getSnapshot 会自动生成 去掉后缀 加上 "_0.jpg"
		//例如
		//1531647260029358080-exercise.mp4
		//1531647260029358080-exercise_0.jpg
		videoUrl := BASE_URL + key
		return videoUrl
	}
	return err.Error()
}

func getClient() *cos.Client {
	f, _ := os.OpenFile("log.txt", os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0777)
	u, _ := url.Parse(fmt.Sprintf(COS_URL_FORMAT, COS_BUCKET_NAME, COS_APP_ID, COS_REGION))
	b := &cos.BaseURL{
		BucketURL: u}
	c := cos.NewClient(b, &http.Client{

		Transport: &cos.AuthorizationTransport{

			SecretID:  COS_SECRET_ID,
			SecretKey: COS_SECRET_KEY,
			Transport: &debug.DebugRequestTransport{

				RequestHeader: true,
				// Notice when put a large file and set need the request body, might happend out of memory error.
				RequestBody:    false,
				ResponseHeader: true,
				ResponseBody:   true,
				Writer:         f,
			},
		},
	})
	print(c.Host)
	return c
}

func log_status(err error) bool {

	if err == nil {

		return true
	}
	if cos.IsNotFoundError(err) {

		// WARN
		fmt.Println("WARN: Resource is not existed")
		return false
	} else if e, ok := cos.IsCOSError(err); ok {

		fmt.Printf("ERROR: Code: %v\n", e.Code)
		fmt.Printf("ERROR: Message: %v\n", e.Message)
		fmt.Printf("ERROR: Resource: %v\n", e.Resource)
		fmt.Printf("ERROR: RequestId: %v\n", e.RequestID)
		return false
		// ERROR
	} else {

		fmt.Printf("ERROR: %v\n", err)
		return false
		// ERROR
	}
}

//可以废弃
func getSnapshot(key string) {
	c := getClient()
	opt := &cos.GetSnapshotOptions{
		Time: 1,
	}
	resp, err := c.CI.GetSnapshot(context.Background(), key, opt)
	if err != nil {
		// ERROR
		fmt.Printf("ERROR:%v\n", err.Error())
	}
	_, err = c.Object.Put(context.Background(), key+".jpg", resp.Body, nil)
	if err != nil {
		// ERROR
		fmt.Printf("ERROR:%v\n", err.Error())
	}
}

//测试
func main() {
	path := "exercise.mp4" //要上传文件所在路径
	file, err := os.Open(path)
	if err != nil {
		print("error")
	}
	videoUrl := UploadFile(file, "exercise.mp4")
	print(videoUrl + "\n")
	defer file.Close()

	//由videoUrl生成预览图URL
	indexOfDot := strings.LastIndex(videoUrl, ".")
	SnapshotUrl := videoUrl[0:indexOfDot] + "_0.jpg"
	fmt.Printf("%v\n", SnapshotUrl)
	//getSnapshot("exercise.mp4")
}
